﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DTO;
using BUS;
using System.Data.SqlClient;


namespace SQLXML
{
    public partial class MainForm : Form
    {
        public static string myPath = null;
        public MainForm()
        {

            InitializeComponent();

            // save path connectionstring.txt
            if (myPath == null)
            {
                FileInfo fileConnect = new FileInfo(@"..\..\ConnectionString.txt");
                if (fileConnect.Exists == true)
                    myPath = fileConnect.FullName;
                ManagerFileBUS.AddMyPath(myPath);
                //UpdateGvData();

            }

            TextReader textReader = new StreamReader(myPath);
            txtConnectionString.Text = textReader.ReadLine();
            textReader.Close();

        }
        private void UpdateGvData()
        {
            gvData.DataSource = ManagerFileBUS.GetAllFile();
            gvData.Update();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult result;
            ChooseFile.Multiselect = true;
            ChooseFile.FileName = "";

            result = ChooseFile.ShowDialog();
            if (result == DialogResult.Cancel)
            {
                return;
            }
            else
            {
                rtbFileUpload.Text = "";
                try
                {
                    // process
                    int index = 1;
                    foreach (string temp in ChooseFile.FileNames)
                    {
                        FileInfo fileInfo = new FileInfo(temp);
                        rtbFileUpload.Text += (index++).ToString()+". "+fileInfo.Name + "\n";
                        ManagerFileDTO fileDTO = new ManagerFileDTO();
                        fileDTO.Extension = fileInfo.Extension;
                        fileDTO.Name = fileInfo.Name;
                        fileDTO.Size = fileInfo.Length;

                        //////////////////////////////////////////////////////////////////////////
                        // data of file
                        //FileStream fileRead = new FileStream(temp, FileMode.Open);
                        //byte[] buffer = new byte[fileRead.Length];
                        //fileRead.Read(buffer, 0, (int)fileRead.Length);
                        //fileDTO.Data = buffer;
                        //fileDTO.Id = ((int)ManagerFileBUS.GetCount() + 1).ToString();
                        //////////////////////////////////////////////////////////////////////////
                        FileStream fileRead = new FileStream(temp, FileMode.Open);
                        byte[] buffer = new byte[fileRead.Length];
                        fileRead.Read(buffer, 0, (int)fileRead.Length);
                        fileDTO.Data = buffer;
                        fileDTO.Id = ((int)ManagerFileBUS.GetCount() + 1).ToString();
                        //////////////////////////////////////////////////////////////////////////
                        ManagerFileBUS.AddFile(fileDTO);
                        
                        UpdateGvData();

                    }

                    MessageBox.Show("Up Successful!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (FileNotFoundException ex)
                {
                    MessageBox.Show("Error" + ex.Message);

                }
                catch (FieldAccessException ex)
                {
                    MessageBox.Show("Error" + ex.Message);
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            string temp = "ConnectionString.txt";
            string pathFileResult = myPath.Remove(myPath.Length - temp.Length);

            //// create File
            //string nameFile = gvData.SelectedRows[0].Cells["NameFile"].Value.ToString();
            string ID = gvData.SelectedRows[0].Cells["ID"].Value.ToString();
            ManagerFileDTO t = ManagerFileBUS.GetFileByID(ID)[0];


            string nameFile = gvData.SelectedRows[0].Cells["NameFile"].Value.ToString();

            //ASCIIEncoding encoding = new ASCIIEncoding();
            //byte[] dataFile = (byte[])(gvData.SelectedRows[0].Cells["DataFile"].Value);
            byte[] dataFile = t.Data;
            //System.IO.MemoryStream memStream = new System.IO.MemoryStream();
            //System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(object[]));
            //serializer.Serialize(memStream, dr.ItemArray);

            //fileDTO.Data = memStream.ToArray();



            FileStream fileWrite = new FileStream(pathFileResult+@"\FolderCreate\" + nameFile, FileMode.OpenOrCreate, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fileWrite);
            bw.Write(dataFile);
            bw.Close();


            //fileRead.Write(buffer, 0, buffer.Length);
            fileWrite.Close();
            //fileRead.Close();

            //System.Diagnostics.Processes.Start
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = pathFileResult + @"\FolderCreate\" + nameFile;
            process.SynchronizingObject = this;
            process.Start();

            // test
            // get byte
            //FileStream fileRead = new FileStream(@"..\..\FolderCreate\tan.bmp", FileMode.OpenOrCreate);
            //byte[] buffer = new byte[fileRead.Length];
            //fileRead.Read(buffer, 0, (int)fileRead.Length);

            //FileStream fileWrite = new FileStream(@"..\..\FolderCreate\tan1.bmp", FileMode.CreateNew, FileAccess.Write);
            //BinaryWriter bw = new BinaryWriter(fileWrite);
            //bw.Write(buffer);
            //bw.Close();
            ////fileRead.Write(buffer, 0, buffer.Length);
            //fileWrite.Close();
            //fileRead.Close();





            
        }

        private void btnExportXML_Click(object sender, EventArgs e)
        {
            // get lick create file result
            try
            {
                string temp = "ConnectionString.txt";
                string pathFileResult = myPath.Remove(myPath.Length - temp.Length);
                ManagerFileBUS.Export2XML("XMLData", pathFileResult);
                MessageBox.Show("Finish!","Information");
            }
            catch(Exception ex)
            {
                MessageBox.Show("Fail! "+ex.Message,"Error");
            }

        }
        //public sealed class FileTemp
        //{
        //    #region Attribute
        //    private string _id;
        //    private string _name;

        //    private string _extension;

        //    private float _size;

        //    #endregion
        //    #region Public Method
        //    public float Size
        //    {
        //        get { return _size; }
        //        set { _size = value; }
        //    }
        //    public string Extension
        //    {
        //        get { return _extension; }
        //        set { _extension = value; }
        //    }
        //    public string Id
        //    {
        //        get { return _id; }
        //        set { _id = value; }
        //    }

        //    public string Name
        //    {
        //        get { return _name; }
        //        set { _name = value; }
        //    }
        //    #endregion
        //}

        private void btnUpdateConnectString_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection connection = new SqlConnection(txtConnectionString.Text);
                connection.Open();
                connection.Close();

            }
            catch (TimeoutException ex)
            {
                MessageBox.Show("Error ConnectionString. Please try again! ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error ConnectionString", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            btbUpload.Enabled = true;



            TextWriter write = new StreamWriter(myPath);
            write.WriteLine(txtConnectionString.Text);
            write.Close();


    
            gvData.DataSource = ManagerFileBUS.GetAllFile();
            
            gvData.Update();

        }

        private void btnImportFromXML_Click(object sender, EventArgs e)
        {
            try
            {
                string temp = "ConnectionString.txt";
                string pathFileResult = myPath.Remove(myPath.Length - temp.Length) + "XMLData.xml";
                ManagerFileBUS.ImprotFromXML(pathFileResult);
                MessageBox.Show("Finish!", "Information");
                UpdateGvData();

            }

            catch (System.Exception ex)
            {
                MessageBox.Show("Error! Please sure Connection String Or File Exits In DataBase", "Information");
            }
         
        }

        private void gvData_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
